package com.test.dao.impl;

import java.util.List;
import org.hibernate.Session;
import com.test.dao.QuestionDao;
import com.test.table.Question;
import com.test.util.HibernateUtil;

public class QuestionDaoImpl implements QuestionDao{

	
	public void addQuestion(Question question){
		Session session = null;
		try{
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.saveOrUpdate(question);
			session.getTransaction().commit();
		}catch(Exception e){
			if(session.getTransaction() != null){
				session.getTransaction().rollback();
			}
		}finally{
			if(session != null){
				session.close();
			}
		}	
	}

	@SuppressWarnings("unchecked")
	public List<Question> getAllQuestions(){
	
		List<Question> result = null;
		Session session = null;
		try{
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			result = session.createQuery("from Question").list();
			session.getTransaction().commit();
		}catch(Exception e){
			if(session.getTransaction() != null){
				session.getTransaction().rollback();
			}
		}finally{
			if(session != null){
				session.close();
			}
		}
		return result;
	}

	public Question getQuestion(int id){
		Question result = null;
		Session session = null;
		try{
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			result  = (Question) session.load(Question.class, id);
			session.getTransaction().commit();
		}catch(Exception e){
			if(session.getTransaction() != null){
				session.getTransaction().rollback();
			}
		}finally{
			if(session != null){
				session.close();
			}
		}
		return result;
	}

	public void deleteQuestion(Question question){
		Session session = null;
		try{
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.delete(question);
			session.getTransaction().commit();
		}catch(Exception e){
			if(session.getTransaction() != null){
				session.getTransaction().rollback();
			}
		}finally{
			if(session != null){
				session.close();
			}
		}	
	}
	
}
